package com.hr.剑指offer.work1;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 周恒哲
 * @date 2020/06/11
 **/
public class 面试题03_数组中重复的数字 {
    //暴力法
    public static int findRepeatNumber(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    res = nums[i];
                }
            }
        }
        return res;
    }

    //排序法
    public static int findRepeatNumber2(int[] nums) {
        int res = 0;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] == nums[i+1]) {
                res = nums[i];
            }
        }
        return res;
    }
    //哈希表Set
    public static int findRepeatNumber3(int[] nums) {
        Set<Integer> set=new HashSet<>();;
        int res=0;
        for (int num : nums) {
            if (!set.contains(num)) {
                set.add(num);
            }else {
                res=num;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 3, 4, 11, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        System.out.println(面试题03_数组中重复的数字.findRepeatNumber3(nums));
    }
}
